﻿/*
*┌────────────────────────────────────────────────┐
*│　描    述：ToldDapperData                                                   
*│　作    者： (Jxw)                                             
*│　版    本：1.0     
*│　功能描述：                                          
*│　创建时间：2021/6/28 14:04:45                        
*└────────────────────────────────────────────────┘
*/

using Dapper;
using Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;

namespace Data
{
    public class ToldDapperData
    {

        public static List<DeviceBindInfo> GetDeviceInfo()
        {
            using (var conn = DapperDBHelper.InitConn())
            {
                string sql = @"select  设备编码 as deviceCode,使用人员 as workNum,设备名称 as deviceType from  TDeviceInfo where 是否有效='1'";

                return conn.Query<DeviceBindInfo>(sql).ToList();
            }
        }


        /// <summary>
        /// 处理响应的结果
        /// </summary>
        /// <param name="retDTO"></param>
        /// <returns></returns>
        public static RetDTO HandleResponseResult(RetDTO retDTO)
        {
            using (var conn = DapperDBHelper.InitConn())
            {
                RetDTO ret = new RetDTO() { ack = new RetCode() };
                try
                {

                    #region 开启事务，以元组形式插入多表数据
                    var param = new List<Tuple<string, object>>();
                    Tuple<string, object> tupel;
                    var sw = new Stopwatch();
                    sw.Start();


                    #region 处理响应结果

                    List<ResItem> resList = retDTO.ack.res;
                    foreach (var item in resList)
                    {

                        #region 处理患者信息
                        if (item.patientInfo != null)
                        {
                            tupel = new Tuple<string, object>(@" INSERT INTO PatientInfoWD VALUES(@guid,@missionId,@name,@gender,@age,@telecom,@nation,@idCard,@marital,@occCode,@medIns,@present,@past,@allergic,@operation,@family,@medicen,@infoType)",
                                                            new
                                                            {
                                                                guid = item.patientInfo.guid,
                                                                missionId = item.patientInfo.guid,
                                                                name = item.patientInfo.name,
                                                                gender = item.patientInfo.gender,
                                                                age = item.patientInfo.age,
                                                                telecom = item.patientInfo.telecom,
                                                                nation = item.patientInfo.nation,
                                                                idCard = item.patientInfo.idCard,
                                                                marital = item.patientInfo.marital,
                                                                occCode = item.patientInfo.occCode,
                                                                medIns = item.patientInfo.medIns,
                                                                present = item.patientInfo.hisrotry.present,
                                                                past = item.patientInfo.hisrotry.past,
                                                                allergic = item.patientInfo.hisrotry.allergic,
                                                                operation = item.patientInfo.hisrotry.operation,
                                                                family = item.patientInfo.hisrotry.family,
                                                                medicen = item.patientInfo.hisrotry.medicen,
                                                                infoType = 0  //2表示社区患者

                                                            });
                            param.Add(tupel);//添加患者基本信息
                        }
                        #endregion

                        #region 处理体征信息
                        if (item.phyInfo != null)
                        {
                            tupel = new Tuple<string, object>(@" INSERT INTO PhyInfoWD VALUES(@guid,@missionId,@examTime,@spo2, @aware,@temp,@pulse,
                                                        @rhythm,@breath,@diastolic,@systolic,@pupilLeft,@pupilRight,@inspect,@test,@diagnosis,@avg,@low,@high,@infoType)",
                                                           new
                                                           {
                                                               //guid = item.guid,
                                                               missionId = item.missionId,
                                                               examTime = item.phyInfo.examTime,
                                                               spo2 = item.phyInfo.spo2,
                                                               aware = item.phyInfo.aware,
                                                               temp = item.phyInfo.temp,
                                                               pulse = item.phyInfo.pulse,
                                                               rhythm = item.phyInfo.rhythm,
                                                               breath = item.phyInfo.breath,
                                                               diastolic = item.phyInfo.bloodPress.diastolic,
                                                               systolic = item.phyInfo.bloodPress.systolic,
                                                               pupilLeft = item.phyInfo.pupil.left,
                                                               pupilRight = item.phyInfo.pupil.right,
                                                               inspect = item.phyInfo.suppExam.inspect,
                                                               test = item.phyInfo.suppExam.test,
                                                               diagnosis = item.phyInfo.diagnosis,
                                                               avg = item.phyInfo.bloodPress.avg,
                                                               low = item.phyInfo.bloodPress.low,
                                                               high = item.phyInfo.bloodPress.high,
                                                               infoType = 0  //2表示社区患者
                                                           });
                            param.Add(tupel);//添加生命体征信息
                        }

                        #endregion

                        #region 处理除颤仪数据
                        if (item.equipData != null)
                        {

                        }
                        #endregion

                        #region 处理心电数据
                        if (item.ecg != null)
                        {

                        }
                        #endregion


                    }



                    #region 患者基本信息

                    #endregion



                    #endregion




                    //调用事物方法：ExecuteTransaction
                    var result = DapperDBContext.ExecuteTransaction(param).Item1;
                    //string text = DapperDBContext.ExecuteTransaction(param).Item2;
                    sw.Stop();

                    #endregion

                    if (result)
                    {
                        //EventUtility.OnShowMsg("120呼救数据请求成功，数据已入库", false);
                        ret.ack.code = "0";
                        ret.ack.text = "处理成功";
                        ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ret.msgId = Guid.NewGuid().ToString();
                        //ret.targetMsgId = commuPatientInfoDTO.msgId;
                    }
                    else
                    {
                        //EventUtility.OnShowMsg("120呼救数据数据请求，插入数据库失败", true);
                        EventUtility.OnShowMsg("处理失败", true);
                        ret.ack.code = "-1";
                        ret.ack.text = "处理失败";
                        ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ret.msgId = Guid.NewGuid().ToString();
                        //LogUtility.Error("PatientPreData", "插入入库失败");
                    }
                }
                catch (Exception ex)
                {
                    EventUtility.OnShowMsg("处理失败", true);
                    ret.ack.code = "-1";
                    ret.ack.text = ex.ToString();
                    ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    ret.msgId = Guid.NewGuid().ToString();
                    LogUtility.Error("HandleResponseResult", ex.ToString());
                }

                return ret;
            }
        }


        /// <summary>
        /// 更新社区患者任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public static bool UpdateCommuPatientTask(TaskDTO task)
        {
            bool result = false;
            using (var conn = DapperDBHelper.InitConn())
            {
                RetDTO ret = new RetDTO() { ack = new RetCode() };
                try
                {

                    #region 开启事务，以元组形式更新多表数据
                    var param = new List<Tuple<string, object>>();
                    Tuple<string, object> tupel;
                    var sw = new Stopwatch();
                    sw.Start();

                    object obj = new
                    {
                        guid = task.zdCode,
                        missionId = task.taskCode
                    };

                    #region 更新社区数据
                    tupel = new Tuple<string, object>(@" update  CommuPatientInfoWD  set  missionId=@missionId where guid=@guid",obj);
                    param.Add(tupel); 



                    #region 更新患者基本信息
                    tupel = new Tuple<string, object>(@" update  PatientInfoWD   set missionId=@missionId where guid=@guid", obj);
                    param.Add(tupel);
                    #endregion

                    #region 更新生命体征信息

                    tupel = new Tuple<string, object>(@" update  PhyInfoWD  set missionId=@missionId where guid=@guid",obj);
                    param.Add(tupel);//添加生命体征信息
                    #endregion

                    #endregion

                    //调用事物方法：ExecuteTransaction
                    result = DapperDBContext.ExecuteTransaction(param).Item1;
                    //string text = DapperDBContext.ExecuteTransaction(param).Item2;
                    sw.Stop();

                    #endregion

                }
                catch (Exception ex)
                {
                    LogUtility.Error("UpdateCommuPatientTask", ex.ToString());
                }
                return result;
            }
        }

        
        /// <summary>
        /// 获取除颤仪数据
        /// </summary>
        /// <param name="taskCode"></param>
        /// <returns></returns>
        public static EquipDataWD GetEquipData(string taskCode) {

            using (var conn = DapperDBHelper.InitConn())
            {
                string sql = $"select * from  EquipDataWD where mpi='{taskCode}'";

                return conn.QuerySingleOrDefault<EquipDataWD>(sql);
            }
        }

    }
}
